<?php
/**
 * Create by chang
 * Date 2019/12/20
 * Time 9:53
 *
 */
namespace app\common\service;

use app\admin\model\User;
use app\admin\model\User as UserModel;
use app\common\model\AgentAdmin;
use app\common\model\AgentShop;
use app\common\model\AgentStock;
use app\common\model\AgentStockRecord;
use app\common\model\Promotion;
use think\Db;
use think\Exception;

class AgentService extends Server {
	
	
	/**
	 * 获取代理库存数量
	 * @param $agentId
	 * @return float|int
	 */
	public static function getStockNumberByAgentId($agentId) {
		return Db::name('agentStock')
			->where(['agent_shop_id' => $agentId])
			->sum('number');
	}
	
	/**
	 * 检测是否有核销权限
	 * @param $userId
	 * @param $level
	 * @param $area
	 * @return array|bool
	 * @throws \think\exception\DbException
	 */
	public function checkDestoryAuth($userId, $level, $area) {
		if($level == UserModel::LEVEL_USER) {
			$adminLevel = AgentAdmin::getAdminLevel($userId);
			if($adminLevel) {
				$userId = $adminLevel['user_id'];
				$level = $adminLevel['role'];
			}
		}
		//广东省的场景店，提货点和发展中心都能核销，其它地区发展中心不能核销
		$roleList = [
			UserModel::LEVEL_SHOP,UserModel::LEVEL_WAREHOUSE
		];
		
		if($area == UserModel::AREA_SZ) {
			$roleList[] = UserModel::LEVEL_CENTER;
		}
		if(!in_array($level, $roleList)) {
			return $this->error('没有权限');
		}
		
		$agent = AgentShop::get(['user_id' => $userId, 'status' => AgentShop::STATUS_Y]);
		if(!$agent) {
			return $this->error('代理不存在或已禁用');
		}
		
		return $this->success($agent, '有权限');
	}
	
	
	/**
	 * 获取代理下级代理ID集合
	 * @param $agentId
	 * @param $parentField //上级的字段
	 * @return array
	 */
	public static function getAgentSubIds($agentId, $parentField) {
		return Db::name('agentShop')
			->where(['status' => AgentShop::STATUS_Y, $parentField => $agentId])
			->column('id', 'user_id');
	}
	
	
	/**
	 * 获取代理的下级代言人ID集合
	 * @param $agentIds
	 * @return array
	 */
	public static function getAgentSubPromotionIds($agentIds) {
		return Db::name('promotion')
			->where(['status' => Promotion::STATUS_Y, 'agent_shop_id' => ['in', $agentIds]])
			->column('id', 'user_id');
		
	}
	
	
	/**
	 * 上级关闭下级代理权限，触发回收库存
	 * @param $userId 操作代理的用户ID
	 * @param $level 操作代理的用户等级
	 * @param $agentId 关闭的代理ID
	 * @return bool
	 * @throws \think\exception\DbException
	 */
	public function closeAgent($userId, $level, $agentId)
	{
		
		$closeAgent = AgentShop::get(['id' => $agentId, 'status' => AgentShop::STATUS_Y]);
		if(!$closeAgent) {
			$this->errorMsg = '操作的代理不存在或已关闭';
			return false;
		}
		//关闭权限，总部清空库存，其它收回库存
		//判断权限
		
		//上级对应的字段
		$field = '';
		$agent = '';
		if($level != User::LEVEL_HEADQUARTERS) {
			//操作人
			$agent = AgentShop::get(['user_id' => $userId, 'status' => AgentShop::STATUS_Y]);
			if(!$agent) {
				$this->errorMsg = '你不是代理';
				return false;
			}
			$agentRole = '';
			switch ($agent['role']) {
				case User::LEVEL_THEATER:
					$field = 'theater_id';
					$agentRole = User::LEVEL_CENTER;
					break;
				case User::LEVEL_CENTER:
					$field = 'center_id';
					$agentRole = User::LEVEL_WAREHOUSE;
					break;
				case User::LEVEL_WAREHOUSE:
					$field = 'warehouse_id';
					$agentRole = User::LEVEL_SHOP;
					break;
				default:
					$this->errorMsg = '你没有权限';
					return false;
			}
			
			$closeAgent = AgentShop::get(['role' => $agentRole, $field => $agent['id'], 'id' => $agentId]);
			if(!$closeAgent) {
				$this->errorMsg = '下属上级才可关闭代理权限';
				return false;
			}
		}
		
		$agentModel = new AgentShop();
		Db::startTrans();
		try {
			//更改代理状态
			$agentRes = $agentModel->save(
				['status' => $agentModel::STATUS_D],
				['id' => $agentId]);
			
			if (!$agentRes) {
				throw new Exception('更改代理状态出错');
			}
			
			
			$where = [
				'agent_shop_id' => $agentId,
				'number' => ['gt', 0]
			];
			
			//操作库存
			$stockList = Db::name('agentStock')
				->where($where)
				->select();
			
			if($stockList) {
				//清空库存
				$removeRes = Db::name('agentStock')
					->where($where)
					->update([
						'number' => 0,
						'update_time' => time()
					]);
				if(!$removeRes) {
					throw new Exception('清空库存出错');
				}
				
				$stockRecoreModel = new AgentStockRecord();
				$stockModel = new AgentStock();
				foreach ($stockList as $item) {
					//添加库存记录
					$removeStockRes = $stockRecoreModel->addRecord($closeAgent['user_id'], $item['goods_id'], $item['spec_id'], $stockRecoreModel::TYPE_OUT, $item['number'], '关闭权限清空库存');
					if(!$removeStockRes) {
						throw new Exception('添加清空库存记录出错');
					}
					
					//如果不是总部，给上级加库存和库存记录
					if($agent) {
						//加库存
						$addStockRes = $stockModel->add($agent['user_id'], $agent['id'], $item['goods_id'], $item['spec_id'], $item['number']);
						if(!$addStockRes) {
							throw new Exception('添加上级库存出错');
						}
						
						$addStockRecoreRes = $stockRecoreModel->addRecord($agent['user_id'], $item['goods_id'], $item['spec_id'], $stockRecoreModel::TYPE_IN, $item['number'], '关闭下级代理回收库存');
						
						if(!$addStockRecoreRes) {
							throw new Exception('添加上级回收记录出错');
						}
						
					}
				}
			}
			
			Db::commit();
			return true;
		} catch (Exception $e) {
			Db::rollback();
			$this->errorMsg = $e->getMessage();
			return false;
		}
		
	}
	
}
